package com.agent.crm.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import xu.ye.dao.ContactDao;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.widget.Toast;

import com.agent.crm.bean.MyContact;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;
import com.agent.crm.view.R;
import com.pwp.activity.StopScheduleByNotificationActivity;
import com.pwp.dao.ScheduleDAO;
import com.pwp.vo.ScheduleVO;

public class MonthYearService extends Service {
	
	private ScheduleDAO dao = null;
	DatabaseManager manager ;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		dao = new ScheduleDAO(this);
		if(null==manager)
			manager = new DatabaseManager(this);
		Thread startThread = new Thread(DWMYSchduleStartTask);
		startThread.start();
	}

	Runnable DWMYSchduleStartTask = new Runnable() {
        public void run() {
        	while(true){
        		List<ScheduleVO> schedules=dao.getAllScheduleCycleMonthOrYear();
            	for (int i = 0; i <schedules.size(); i++) {
            		ScheduleVO scheduleVO=(schedules.get(i));
            		String nextTimeWakeUp=scheduleVO.getScheduleStartDate();
            		Date d=new Date();
                	if(d.before(formatStringToDate(schedules.get(i).getScheduleStartDate()))){
                		continue;
                	}
    				if("M".equalsIgnoreCase(scheduleVO.getScheduleCycleType())){
    					if(scheduleVO.getScheduleTypeID()==5){
    						//发送短信
    						String SENT_SMS_ACTION = "SENT_SMS_ACTION";   
    						Intent sentIntent = new Intent(SENT_SMS_ACTION);   
    						PendingIntent sentPI = PendingIntent.getBroadcast(MonthYearService.this, 0, sentIntent,   
    						        0);   
    						String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";   
    						// create the deilverIntent parameter   
    						Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);   
    						PendingIntent deliverPI = PendingIntent.getBroadcast(MonthYearService.this, 0,   
    						       deliverIntent, 0);   
    						if(null!=scheduleVO.getScheduleObjectID()&&!"".equalsIgnoreCase(scheduleVO.getScheduleObjectID())){
    							SmsManager smsManager = SmsManager.getDefault();   
    							String[] listObjectID =String.valueOf(scheduleVO.getScheduleObjectID()).split(",");
    							List<String> listMobileNum =new ArrayList<String>();
    							if("0".equalsIgnoreCase(scheduleVO.getScheduleMode())){
    								//单人任务，通过objectID从人员表中查询号码
    								listMobileNum=getObjectTel(listObjectID, "0");
    							}else if("1".equalsIgnoreCase(scheduleVO.getScheduleMode())){
    								//分类任务，通过objectID从人员表和分类表关联结果中查询号码
    								listMobileNum=getObjectTel(listObjectID, "1");
    							}else{
    								//群组任务，通过objectID从人员表和群组表关联记过中查询号码
    								listMobileNum=getObjectTel(listObjectID, "2");
    							}
    							for (int j = 0; j < listMobileNum.size(); j++) {
    								smsManager.sendTextMessage(listMobileNum.get(j), null, scheduleVO.getScheduleContent(), sentPI, deliverPI);  
    							} 
    						}
    				        Notification n=new Notification(R.drawable.bg_tab_dial_pressed_up,scheduleVO.getScheduleTitle(), System.currentTimeMillis());
    				        Intent intent=new Intent(MonthYearService.this,StopScheduleByNotificationActivity.class);
    				        intent.putExtra("scheduleId", scheduleVO.getScheduleID());
    				        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    				        intent.setData(Uri.parse("custom://"+System.currentTimeMillis()));//这行代码会解决notification传到StopScheduleByNotificationActivity参数不更新问题
    				        PendingIntent pIntent=PendingIntent.getActivity(MonthYearService.this, 0,intent, 0);
    				        n.defaults=Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
    				        n.setLatestEventInfo(MonthYearService.this,"短信任务："+scheduleVO.getScheduleTitle()+"已发送",scheduleVO.getScheduleContent(), pIntent);
    				        NotificationManager nm=(NotificationManager)MonthYearService.this.getSystemService(Context.NOTIFICATION_SERVICE);
    				        nm.notify(scheduleVO.getScheduleID(), n);
    					}else{
//    				        Toast.makeText(MonthYearService.this,scheduleVO.getScheduleTitle(), Toast.LENGTH_SHORT).show();
    						Intent intent=new Intent(MonthYearService.this,StopScheduleByNotificationActivity.class);
    				        intent.putExtra("scheduleId", scheduleVO.getScheduleID());
    				        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    				        intent.setData(Uri.parse("custom://"+System.currentTimeMillis()));//这行代码会解决notification传到StopScheduleByNotificationActivity参数不更新问题
    				        Notification n=new Notification(R.drawable.bg_tab_dial_pressed_up,scheduleVO.getScheduleTitle(), System.currentTimeMillis());
    				        PendingIntent pIntent=PendingIntent.getActivity(MonthYearService.this, 0,intent, 0);
    				        n.defaults=Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
    				        n.setLatestEventInfo(MonthYearService.this,scheduleVO.getScheduleTitle(),scheduleVO.getScheduleContent(), pIntent);
    				        NotificationManager nm=(NotificationManager)MonthYearService.this.getSystemService(Context.NOTIFICATION_SERVICE);
    				        nm.notify(scheduleVO.getScheduleID(), n);
    					}
    					Calendar c=Calendar.getInstance();
    					c.clear();
    					c.setTime(formatStringToDate(scheduleVO.getScheduleStartDate()));
    					TimeZone tz = TimeZone.getTimeZone("GMT");        
                        c.setTimeZone(tz); 
                        c.set(Calendar.MONTH, c.get(Calendar.MONTH)+1);
    					nextTimeWakeUp =new SimpleDateFormat("yyyy-MM-dd HH:mm").format(c.getTime());
    				}else if("Y".equalsIgnoreCase(scheduleVO.getScheduleCycleType())){
    					if(scheduleVO.getScheduleTypeID()==5){
    						//发送短信
    						String SENT_SMS_ACTION = "SENT_SMS_ACTION";   
    						Intent sentIntent = new Intent(SENT_SMS_ACTION);   
    						PendingIntent sentPI = PendingIntent.getBroadcast(MonthYearService.this, 0, sentIntent,   
    						        0);   
    						String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";   
    						// create the deilverIntent parameter   
    						Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);   
    						PendingIntent deliverPI = PendingIntent.getBroadcast(MonthYearService.this, 0,   
    						       deliverIntent, 0);   
    						if(null!=scheduleVO.getScheduleObjectID()&&!"".equalsIgnoreCase(scheduleVO.getScheduleObjectID())){
    							SmsManager smsManager = SmsManager.getDefault();   
    							String[] listObjectID =String.valueOf(scheduleVO.getScheduleObjectID()).split(",");
    							List<String> listMobileNum =new ArrayList<String>();
    							if("0".equalsIgnoreCase(scheduleVO.getScheduleMode())){
    								//单人任务，通过objectID从人员表中查询号码
    								listMobileNum=getObjectTel(listObjectID, "0");
    							}else if("1".equalsIgnoreCase(scheduleVO.getScheduleMode())){
    								//分类任务，通过objectID从人员表和分类表关联结果中查询号码
    								listMobileNum=getObjectTel(listObjectID, "1");
    							}else{
    								//群组任务，通过objectID从人员表和群组表关联记过中查询号码
    								listMobileNum=getObjectTel(listObjectID, "2");
    							}
    							for (int j = 0; j < listMobileNum.size(); j++) {
    								smsManager.sendTextMessage(listMobileNum.get(j), null, scheduleVO.getScheduleContent(), sentPI, deliverPI);  
    							} 
    						}  
//    						Toast.makeText(MonthYearService.this,"短信任务："+scheduleVO.getScheduleTitle()+"已发送", Toast.LENGTH_SHORT).show();
    				        Notification n=new Notification(R.drawable.bg_tab_dial_pressed_up,scheduleVO.getScheduleTitle(), System.currentTimeMillis());
    				        Intent intent=new Intent(MonthYearService.this,StopScheduleByNotificationActivity.class);
    				        intent.putExtra("scheduleId", scheduleVO.getScheduleID());
    				        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    				        intent.setData(Uri.parse("custom://"+System.currentTimeMillis()));//这行代码会解决notification传到StopScheduleByNotificationActivity参数不更新问题
    				        PendingIntent pIntent=PendingIntent.getActivity(MonthYearService.this, 0,intent, 0);
    				        n.defaults=Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
    				        n.setLatestEventInfo(MonthYearService.this,"短信任务："+scheduleVO.getScheduleTitle()+"已发送",scheduleVO.getScheduleContent(), pIntent);
    				        NotificationManager nm=(NotificationManager)MonthYearService.this.getSystemService(Context.NOTIFICATION_SERVICE);
    				        nm.notify(scheduleVO.getScheduleID(), n);
    					}else{
    						Intent intent=new Intent(MonthYearService.this,StopScheduleByNotificationActivity.class);
    				        intent.putExtra("scheduleId", scheduleVO.getScheduleID());
    				        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    				        intent.setData(Uri.parse("custom://"+System.currentTimeMillis()));//这行代码会解决notification传到StopScheduleByNotificationActivity参数不更新问题
//    						Toast.makeText(MonthYearService.this,scheduleVO.getScheduleTitle(), Toast.LENGTH_SHORT).show();
    				        Notification n=new Notification(R.drawable.bg_tab_dial_pressed_up,scheduleVO.getScheduleTitle(), System.currentTimeMillis());
    				        PendingIntent pIntent=PendingIntent.getActivity(MonthYearService.this, 0,intent, 0);
    				        n.defaults=Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
    				        n.setLatestEventInfo(MonthYearService.this,scheduleVO.getScheduleTitle(),scheduleVO.getScheduleContent(), pIntent);
    				        NotificationManager nm=(NotificationManager)MonthYearService.this.getSystemService(Context.NOTIFICATION_SERVICE);
    				        nm.notify(scheduleVO.getScheduleID(), n);
    					}
    					Calendar c=Calendar.getInstance();
    					c.clear();
    					c.setTime(formatStringToDate(scheduleVO.getScheduleStartDate()));
    					TimeZone tz = TimeZone.getTimeZone("GMT");        
                        c.setTimeZone(tz); 
                        c.set(Calendar.YEAR, c.get(Calendar.YEAR)+1);
    					nextTimeWakeUp =new SimpleDateFormat("yyyy-MM-dd HH:mm").format(c.getTime());
    				}else{
    					
    				}
    				if(formatStringToDate(nextTimeWakeUp).after(formatStringToDate(schedules.get(i).getScheduleEndDate()))){
    					dao.resetScheduleStatusFlagsToFinished(scheduleVO.getScheduleID());
                	}else{
                		dao.resetScheduleStatusFlags(scheduleVO.getScheduleID(),"1");
        				dao.updateMAndYSchedleStartDate(scheduleVO.getScheduleID(),nextTimeWakeUp);
                	}
    			}
            	try {
    				Thread.sleep(60*1000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
        	}
        }
    };
    
    private List<String> getObjectTel(String[] listObjectID,String mode){
		SQLiteDatabase sqlLite = manager.getWritableDatabase();
		ContactDao cDao =new ContactDao(this);
		List<String> list = new ArrayList<String>();
		if("0".equalsIgnoreCase(mode)){
			for (int i = 0; i < listObjectID.length; i++) {
				Cursor cursor = sqlLite.query(DBInitScript.Table_ContactsInfo, new String[]{"mobile_phone"}, " contacts_id =?", new String[]{listObjectID[i]}, null, null, null, null);
				int count = cursor.getCount();
			    if(count == 0){
		        }else{
		        	while (cursor.moveToNext()) {
		        		String mobilePhone = cursor.getString(cursor.getColumnIndex("mobile_phone"));
			        	list.add(mobilePhone);
					}
		        }
			    cursor.close();
			}
		}
		if("1".equalsIgnoreCase(mode)){
			for (int i = 0; i < listObjectID.length; i++) {
				List<MyContact> contact=cDao.getContactsByTypeId(Integer.valueOf(listObjectID[i]));
				if(null==contact){
					break;
				}
				for (int j = 0; j < contact.size(); j++) {
					list.add(contact.get(j).getMobilePhone());
				}
			}
		}
		if ("2".equalsIgnoreCase(mode)) {
			for (int i = 0; i < listObjectID.length; i++) {
				List<MyContact> contact=cDao.getContactsByGroupId(Integer.valueOf(listObjectID[i]));
				if(null==contact){
					break;
				}
				for (int j = 0; j < contact.size(); j++) {
					list.add(contact.get(j).getMobilePhone());
				}
			}
		}
		sqlLite.close();
		return list;
	}
    private Date formatStringToDate(String str){
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return format.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			return format.parse(format.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new Date();
	}
}
